<style lang="less">
  .detailInputBox{
    .el-form--inline {
      .el-form-item{
        width: 35%;
        .el-input__inner{
          color: rgb(31, 55, 61);
        }
      }
      .el-form-item__label{
        width: 7rem;
      }
      .el-form-item__content{
        width: 70%;
        .el-select{
          width:100%;
        }
        .el-input-group__append{
          color: #333;
        }
      }
      .color-picker{
          .el-color-picker{
            width: 5rem;
          }
          .el-input{
            position: absolute;
            width: 80%;
          }
        }
    }
    .separate{
      color: #f7931e;
      font-size: 16px;
      font-weight: bold;
    }
    .btnBox{
      padding: 2rem 0 1rem 7rem;
    }
  }

</style>

<template>
  <div class="detailInputBox">
    <el-form :inline="true" :rules='rules' :model="formData" ref='form'>
      <el-form-item label="产品编码" prop='productNo'>
        <el-input :disabled='disabled' v-model.trim="formData.productNo" placeholder="请输入产品编码"></el-input>
      </el-form-item>

      <el-form-item label="产品名称" prop='productName'>
        <el-input v-model.trim="formData.productName"  :disabled='disabled' placeholder="请输入产品名称"></el-input>
      </el-form-item>

      <el-form-item label="最高收益" prop='maxRate'>
        <el-input v-model.trim="formData.maxRate"  :disabled='disabled' placeholder="请输入收益率"></el-input>
      </el-form-item>

      <el-form-item label="最低收益" prop='minRate'>
        <el-input v-model.trim="formData.minRate"  :disabled='disabled' placeholder="请输入收益率"></el-input>
      </el-form-item>

      <el-form-item label="总募集额度" prop='raiseLimit'>
        <el-input v-model.number="formData.raiseLimit"  :disabled='disabled' placeholder="请输入总募集额度">
          <template slot="append">万</template>
        </el-input>
      </el-form-item>

      <el-form-item label="起购金额" prop='minPurchaseAmount'>
        <el-input v-model.number="formData.minPurchaseAmount"  :disabled='disabled' placeholder="请输入起购金额">
          <template slot="append">万</template>
        </el-input>
      </el-form-item>
      <el-form-item label="发行方" prop='issuerId'>
        <el-select v-model="formData.issuerId" :disabled='disabled' placeholder="请选择">
          <el-option :key='item.id' :label='item.name' :value="item.id " v-for='(item, index) in issuerList'></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="产品期限" prop='productTermStr'>
        <el-input v-model.trim="formData.productTermStr"  :disabled='disabled' placeholder="请输入产品期限"></el-input>
      </el-form-item>

      <el-form-item label="风险等级" prop='riskLevel'>
        <el-select v-model="formData.riskLevel"  :disabled='disabled' placeholder="请选择">
          <el-option :key='item.level' :label='item.name' :value="item.level" v-for='(item, index) in riskLevel'></el-option>
        </el-select>
      </el-form-item>

      <div class="separate">产品标签</div>
      <el-form-item label="标签1" prop='label01'>
        <el-input v-model="formData.label01"  :disabled='disabled' placeholder="请输入标签，最多4个文字"></el-input>
      </el-form-item>
      <el-form-item label="颜色" class="color-picker" prop='labelColor01'>
        <el-color-picker v-model="formData.labelColor01"  v-if='!disabled' ></el-color-picker>
        <el-input v-model.trim="formData.labelColor01"  :disabled='disabled' placeholder="请输入7位颜色值"></el-input>
      </el-form-item>
      
      <el-form-item label="标签2" prop='label02'>
        <el-input v-model="formData.label02"  :disabled='disabled' placeholder="请输入标签，最多4个文字"></el-input>
      </el-form-item>
      <el-form-item label="颜色" class="color-picker" prop='labelColor02'>
        <el-color-picker v-model="formData.labelColor02" v-if='!disabled' ></el-color-picker>
        <el-input v-model.trim="formData.labelColor02"  :disabled='disabled' placeholder="请输入7位颜色值"></el-input>
      </el-form-item>

      <el-form-item label="标签3" prop='label03'>
        <el-input v-model="formData.label03"  :disabled='disabled' placeholder="请输入标签，最多4个文字"></el-input>
      </el-form-item>
      <el-form-item label="颜色" class="color-picker" prop='labelColor03'>
        <el-color-picker v-model="formData.labelColor03" v-if='!disabled' ></el-color-picker>
        <el-input v-model.trim="formData.labelColor03"  :disabled='disabled' placeholder="请输入7位颜色值"></el-input>
      </el-form-item>

      <el-form-item label="标签4" prop='label04'>
        <el-input v-model="formData.label04"  :disabled='disabled' placeholder="请输入标签，最多4个文字"></el-input>
      </el-form-item>
      <el-form-item label="颜色" class="color-picker" prop='labelColor04'>
        <el-color-picker v-model="formData.labelColor04" v-if='!disabled' ></el-color-picker>
        <el-input v-model.trim="formData.labelColor04"  :disabled='disabled' placeholder="请输入7位颜色值"></el-input>
      </el-form-item>

      <br/>

      <div class="btnBox">
        <el-button @click='goPage("privatePlacementList")'>取消</el-button>
        <el-button type="primary" @click='submit' v-if="this.$route.name !='privatePlacementListCheck'">确定</el-button>
      </div>
    </el-form>
  </div>
</template>


<script>
  import {postAddPrivateProduct, postPPBaseInfo} from 'api/privatePlacement'
  import {inputRule ,riskLevelArr} from '../config.js'
  import {postLog, getIssuerId} from 'api/common'

  export default {
    props:['formDisabled','formData'],
    data(){
      var validLabelColor = (rule, value, callback) => {
          const labelNum = rule.field.substr(rule.field.length - 1, 1) //取lebelColor最后一位
          if(this.formData['label0' + labelNum]){
            let color = this.formData['labelColor0' + labelNum];
            // console.log(labelNum , color, /^#[0-9a-fA-F]{3,6}$/.test(color))
            if( !color || !(/^#[0-9a-fA-F]{3,6}$/.test(color)) ){
              return callback(new Error('请选择颜色'))
            }
          }
          callback()
      };
      /**
       * 最高收益 最低收益判断规则：
       * 1、只支持百分比、文字格式
       * 2、在同一输入框里输入“百分比+文字”格式，如“7浮动收益”或“7%浮动收益”也不予以保存。文案提示【请正确输入格式】
       * 3、当最低收益输入文字时，判断好最高收益为相同的文字；当最低收益输入数字时，最高收益可输入数字或文字
       * **/
      var validMaxRate = (rule, value, callback) =>{
        // console.log('validMaxRate', value)
        if(/[0-9]/.test(value)){
          //判断是否有数字
          if(/[a-z]/i.test(value) || /[\u4e00-\u9fa5]/.test(value)){
            callback(new Error('请正确输入格式'))
          }else if(/^(100|[1-9]?\d(\.\d\d?\d?)?)%$|0$/.test(value)){
            callback()
          }else{
            callback(new Error('请正确输入格式'))
          }
        }else{
          callback()
        }
      }
      var validMinRate = (rule, value, callback) =>{
        // console.log('validMinRate', value,'maxRate => ',this.formData.maxRate)
        if(/[0-9]/.test(value)){
          //判断是否有数字
          if(/[a-z]/i.test(value) || /[\u4e00-\u9fa5]/.test(value)){
            callback(new Error('请正确输入格式'))
          }else if(/^(100|[1-9]?\d(\.\d\d?\d?)?)%$|0$/.test(value)){
            callback()
          }else{
            callback(new Error('请正确输入格式'))
          }
        }else {
          if(value !== this.formData.maxRate){
            callback(new Error('必须和最高收益一致'))
          }else{
            callback()
          }
        }
      }
      var customValid ={
        labelColor01: [{ validator: validLabelColor, trigger: 'blur' }],
        labelColor02: [{ validator: validLabelColor, trigger: 'blur' }],
        labelColor03: [{ validator: validLabelColor, trigger: 'blur' }],
        labelColor04: [{ validator: validLabelColor, trigger: 'blur' }],
        maxRate: [
            { required: true, message: '请输入收益率', trigger: 'blur' },
            { validator: validMaxRate, trigger: 'blur' },
        ],
        minRate: [
            { required: true, message: '请输入收益率', trigger: 'blur' },
            { validator: validMinRate, trigger: 'blur' },
        ],
      };
      return{
        productId:this.$route.query && this.$route.query.productId ? this.$route.query.productId : null,
        riskLevel:riskLevelArr,
        rules:Object.assign(customValid, inputRule),
        issuerList:[],
      }
    },
    computed:{
      disabled(){
        let id = this.$route.query && this.$route.query.productId ? this.$route.query.productId :null
        if(id && this.$route.name =='addNewPP') return true //创建时，如果有id就不能修改！
        if(this.$route.name =='privatePlacementListCheck') return true //查看时不能编辑！
        return this.formDisabled
      }
    },
    watch:{
      '$route':function(val, oldV){
        // console.log('$route', val, oldV)
        let id = val.query.productId && val.query.productId ? val.query.productId :'',
            oldId = oldV.query.productId && oldV.query.productId ? oldV.query.productId :'';
        console.warn(id, oldId)
        if(id != oldId){
          this.productId = id;
        }
      },
    },
    methods:{
      async getIssuerId(){
        try{
          let back = await getIssuerId()
          back = back.data;
          console.log('getIssuerId',back)
          if(back && back.resultCode ==='200'){
            this.issuerList = back.result;
          }else{
            this.$message({
                message: '发行方获取失败' + back.msg,
                type: 'warning'
            });
          }
        }catch(err){
          this.$message({
              message: '发行方获取失败！',
              type: 'warning'
          });
          console.error(err)
        }
      },
      submit(){
        this.$refs.form.validate((valid) => {
          if (valid) {
            console.log('submit!');
            this.postFun()
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      setIssuerName(id){//创建时要传发行方的名字
        let issuerList = this.issuerList
        for(let i = 0; i<issuerList.length;i++){
          if(issuerList[i].id == id) {
            return issuerList[i].name
          }
        }
      },
      async postFun(){
        try{
          if(this.$route.name == 'addNewPP' && this.$route.query && this.$route.query.productId ){
            return
          }
          let tempObj = {
            issuerName:this.setIssuerName(this.formData.issuerId),
            productId:this.formData.id
          },back, pageName;
          let params = Object.assign(this.formData, tempObj)
          if(this.$route.name == 'addNewPP'){
            pageName='addNewPP'
            back = await postAddPrivateProduct(params)
          }else if(this.$route.name == 'privatePlacementListEdit'){
            pageName='privatePlacementListEdit'
            back = await postPPBaseInfo(params)
          }else{
            return
          }
          back = back.data;
          console.warn('postFun', this.$route.name, this.formData, back)
          if(back && back.resultCode =='200'){
            this.$alert(back.msg,{
              callback:action=>{
                let query = {
                  productId:this.productId ? this.productId : back.result.id,
                }
                this.goPage(pageName, query)
              }
            })
            //发送日志
            let btnName = this.$route.name == 'addNewPP' ? 'PRIVATE_PLACEMENT_LIST_CREATE' : 'PRIVATE_PLACEMENT_LIST_EDIT';
            let id = back.result && back.result.id ? back.result.id:this.formData.id;
            let productName = back.result && back.result.productName ? back.result.productName:this.formData.productName;
            postLog(btnName, id, productName, params)

          }else{
            this.$alert(back.msg)
          }
        }catch(err){
          console.error(err)
        }
      },
      nextFun(id){
        let query = {
          productId:id,
        }
        this.$confirm('创建成功','提示',{
          confirmButtonText: '下一步',
          cancelButtonText: '确定',
        }).then(()=>{
          sessionStorage.setItem('ppActiveTap','INTRODUCE')
          this.goPage('addNewPP', query)
        }).catch(()=>{
          this.goPage('addNewPP', query)
          console.log('取消！')
        })
      },
      goPage(name, query){
        this.$router.push({
          name:name,
          query:query
        })
      }

    },
    created(){
      this.getIssuerId()
    }
    
  }
</script>
